﻿using Core.Event;
using Core.Librarys;
using Core.Models.Config;
using Core.Servicers.Interfaces;
using FileSC.Configs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Core.Servicers.Instances
{
    public class AppConfig2 : IAppConfig2
    {
        private string fileName;
        private ConfigModel config;

        public event AppConfigEventHandler ConfigChanged;
        private ConfigModel oldConfig;

        public AppConfig2()
        {
            fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                "app.config.xlsx");
        }
        public void Load()
        {
            string configText = string.Empty;
            try
            {
                if (! File.Exists(fileName))
                {
                    //  创建基础配置
                    CreateDefaultConfig();

                    Save();
                }
                config = new ConfigModel();
                config.General = new GeneralModel
                {
                    Theme = 0,
                    IsStartatboot = AppConfig.YesOrNo("开机自启动"),
                    ThemeColor = AppConfig.Text("主色调"),
                    IsSaveWindowSize = AppConfig.YesOrNo("保留窗口大小"),
                    WindowWidth = double.Parse(AppConfig.Text("窗口宽度")),
                    WindowHeight = double.Parse(AppConfig.Text("窗口高度")),
                    StartPage = int.Parse(AppConfig.Text("启动页")),
                    IsStartupShowMainWindow = AppConfig.YesOrNo("启动显示窗口")
                };
                if (AppConfig.Text("主题") == "深色")
                {
                    config.General.Theme = 1;
                }
                config.Download = new DownloadModel
                {
                    IsOpenAfterDownload = AppConfig.YesOrNo("下载后打开文件夹")
                };


                CopyToOldConfig();

                CheckOption(config);
            }
            catch (JsonSerializationException ex)
            {
                HandleLoadFail(ex.Message, configText);
            }
            catch (JsonReaderException ex)
            {
                HandleLoadFail(ex.Message, configText);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }

        private void CopyToOldConfig()
        {
            string configStr = JsonConvert.SerializeObject(config);
            oldConfig = JsonConvert.DeserializeObject<ConfigModel>(configStr);
        }

        private void HandleLoadFail(string err, string configText)
        {
            //  创建基础配置
            CreateDefaultConfig();

            Save();

            Logger.Error(err + "\r\nConfig content: " + configText);
        }
        private void CreateDefaultConfig()
        {
            config = new ConfigModel();
            config.Links = new List<Models.Config.Link.LinkModel>();

            config.General = new GeneralModel();
            config.General.IsStartatboot = false;

            config.Behavior = new BehaviorModel();
            config.Download = new DownloadModel();
        }

        public ConfigModel GetConfig()
        {
            return config;
        }


        public void Save()
        {
            try
            {
                if(config.General.Theme == 0)
                {
                    AppConfig.WriteText("主题", "浅色");
                }
                else
                {
                    AppConfig.WriteText("主题", "深色");
                }
                AppConfig.WriteYesOrNo("开机自启动", config.General.IsStartatboot);
                AppConfig.WriteText("主色调", config.General.ThemeColor);
                AppConfig.WriteYesOrNo("保留窗口大小", config.General.IsSaveWindowSize);
                AppConfig.WriteText("窗口宽度", config.General.WindowWidth.ToString());
                AppConfig.WriteText("窗口高度", config.General.WindowHeight.ToString());
                AppConfig.WriteText("启动页", config.General.StartPage.ToString());
                AppConfig.WriteYesOrNo("启动显示窗口", config.General.IsStartupShowMainWindow);

                AppConfig.WriteYesOrNo("下载后打开文件夹", config.Download.IsOpenAfterDownload);

                ConfigChanged?.Invoke(oldConfig ?? config, config);

                CopyToOldConfig();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }

        private void CheckOption(object obj)
        {
            System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(obj, null);
                if (value == null)
                {
                    //配置项不存在时创建
                    Type[] types = new Type[0];
                    object[] objs = new object[0];

                    ConstructorInfo ctor = item.PropertyType.GetConstructor(types);
                    if (ctor != null)
                    {
                        object instance = ctor.Invoke(objs);
                        item.SetValue(obj, instance);
                    }
                }
            }
        }
    }
}
